package com.ysm.freestyle.activity

import android.annotation.SuppressLint
import android.os.Bundle
import android.os.SystemClock
import android.util.Log
import android.view.LayoutInflater
import androidx.activity.enableEdgeToEdge
import androidx.activity.viewModels
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import androidx.databinding.DataBindingUtil
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.blankj.utilcode.util.LogUtils
import com.blankj.utilcode.util.TimeUtils
import com.ysm.freestyle.R
import com.ysm.freestyle.ScanResultBindingAdapter
import com.ysm.freestyle.databinding.ActivityScanResultBinding
import com.ysm.freestyle.utils.ScanFileNewUtil
import com.ysm.freestyle.utils.TYPE_ALL_TEXT
import com.ysm.freestyle.utils.TYPE_IMAGE_TEXT
import com.ysm.freestyle.viewmodel.FileScanViewModel
import com.ysm.freestyle.viewmodel.PathTextViewModel
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.MainScope
import kotlinx.coroutines.launch

class ScanResultActivity : AppCompatActivity() {
    private var scanUtil: ScanFileNewUtil? = null
    val pathTextViewModel: PathTextViewModel by viewModels()
    val fileScanViewModel: FileScanViewModel by viewModels()
    private lateinit var binding : ActivityScanResultBinding

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()
        //ViewBinding
//        binding = ActivityScanResultBinding.inflate(LayoutInflater.from(this))
//        setContentView(binding.root)

        //DataBinding
        binding = DataBindingUtil.setContentView<ActivityScanResultBinding>(this,R.layout.activity_scan_result)
        binding.lifecycleOwner = this

        initScan()
    }


    @SuppressLint("NotifyDataSetChanged")
    private fun initScan() {
        fileScanViewModel.initScanResultData()

        binding.recycleViewList.layoutManager = LinearLayoutManager(this)
        val adapter = ScanResultBindingAdapter(fileScanViewModel.scanResults.value!!)
        binding.recycleViewList.adapter = adapter

        fileScanViewModel.scanResults.observe(this){
            Log.i("PhotosScan","数据 -> ${it.toList().toString()}")
            binding.recycleViewList.adapter?.notifyDataSetChanged()
        }

        pathTextViewModel.getData().observe(this) {
            //更新页面扫描路径显示
            binding.tvPath.text = "扫描路径: $it"
        }

        MainScope().launch {
            fileScanViewModel.getFlow().collect { size ->
                //更新扫描的文件个数
                binding.tvScanning.text = "Scanning (${size})..."
            }
        }
        scanUtil = ScanFileNewUtil(applicationContext, fileScanViewModel, pathTextViewModel)
        scanFile()
    }

    private var scanningTime = 0L
    private var scanJob: Job? = null
    private fun scanFile() {
        scanningTime = SystemClock.elapsedRealtime()
        scanJob = CoroutineScope(Dispatchers.Default).launch {

//            scanUtil?.getAllFilesDeep(TYPE_ALL_TEXT)

            scanUtil?.getAllFilesNormal(TYPE_IMAGE_TEXT)

            //按序执行，上面扫描完成后才会往下执行所以直接在这里写结束逻辑
            //扫描完成,跳转
            if (!isFinishing) {
                Log.i("ScanFileNewUtil","扫描完成,扫描到数量：  => ${fileScanViewModel.scanFileList.size} " +
                        "总扫描时长 ${ TimeUtils.millis2String(SystemClock.elapsedRealtime() - scanningTime, "HH:mm:ss")}" )

//                LogUtils.e("扫描完成,扫描到数量：",  fileScanViewModel.scanFileList.size,
//                    "总扫描时长：", TimeUtils.millis2String(SystemClock.elapsedRealtime() - scanningTime, "HH:mm:ss")
//                )
//                finish()
            }
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        scanJob?.cancel()
        scanJob = null
        scanUtil?.destroy()
        scanUtil = null
    }
}